<template>
  <div class="chat-container">
    <t-card title="AI 对话" class="chat-card">
      <!-- 聊天历史记录区域 -->
      <div class="chat-history" ref="chatHistory">
        <t-loading :loading="loading">
          <template v-for="(message, index) in chatHistory" :key="index">
            <div :class="['message-item', message.role === 'user' ? 'user-message' : 'ai-message']">
              <t-avatar :image="message.role === 'user' ? userAvatar : aiAvatar" />
              <div class="message-content">
                <t-tag theme="default" variant="light" class="role-tag">
                  {{ message.role === 'user' ? '用户' : 'AI助手' }}
                </t-tag>
                <div class="message-text">
                  {{ message.content }}
                </div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
          </template>
        </t-loading>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <t-input
          v-model="userInput"
          placeholder="请输入您的问题..."
          :disabled="loading"
          @keyup.enter="sendMessage"
        >
          <template #suffix>
            <t-button
              theme="primary"
              :loading="loading"
              :disabled="!userInput.trim()"
              @click="sendMessage"
            >
              发送
            </t-button>
          </template>
        </t-input>
      </div>
    </t-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';

// 定义消息类型
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  time: string;
}

// 状态管理
const loading = ref(false);
const userInput = ref('');
const chatHistory = ref<ChatMessage[]>([]);
const chatHistoryRef = ref<HTMLElement | null>(null);

// 头像配置
const userAvatar = 'https://tdesign.gtimg.com/starter/avatar-user.png';
const aiAvatar = 'https://tdesign.gtimg.com/starter/avatar-ai.png';

// 获取当前时间
const getCurrentTime = () => {
  return new Date().toLocaleTimeString();
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight;
    }
  }, 100);
};

// 发送消息
const sendMessage = async () => {
  const message = userInput.value.trim();
  if (!message || loading.value) return;

  // 添加用户消息
  chatHistory.value.push({
    role: 'user',
    content: message,
    time: getCurrentTime(),
  });

  userInput.value = '';
  loading.value = true;
  scrollToBottom();

  try {
    // 模拟AI响应
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 添加AI响应
    chatHistory.value.push({
      role: 'assistant',
      content: `这是一个模拟的AI响应，实际使用时请替换为真实的API调用。您说：${message}`,
      time: getCurrentTime(),
    });
  } catch (error) {
    MessagePlugin.error('发送消息失败，请重试');
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

// 组件挂载时添加欢迎消息
onMounted(() => {
  chatHistory.value.push({
    role: 'assistant',
    content: '你好！我是AI助手，有什么可以帮你的吗？',
    time: getCurrentTime(),
  });
});
</script>

<style scoped>
.chat-container {
  padding: 20px;
  height: 100%;
}

.chat-card {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message-content {
  flex: 1;
  max-width: 80%;
}

.role-tag {
  margin-bottom: 4px;
}

.message-text {
  padding: 12px;
  border-radius: 8px;
  background: var(--td-bg-color-container);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  white-space: pre-wrap;
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  color: var(--td-text-color-placeholder);
  margin-top: 4px;
}

.user-message .message-text {
  background: var(--td-brand-color-1);
}

.input-area {
  padding: 20px;
  border-top: 1px solid var(--td-component-stroke);
}
</style>